import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.awt.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * @author david
 *
 */
public class GUI implements Icon{
/**
 * Displays the GUI
 */
	String adbPath;
	String choice="";
	String usrInput;
	String usrInput2;
	Thread t = new Thread();
	JFileChooser browser = new JFileChooser();
	FileNameExtensionFilter apk = new FileNameExtensionFilter(
		        "Android Installation Packages", "apk");
	FileNameExtensionFilter allFiles = new FileNameExtensionFilter(
	        "Any File type", "*");
	final String ver ="0.5b";
GUI() throws InterruptedException{
	
	
	
	try{
		BufferedReader os = new BufferedReader(new FileReader("os.txt")); //	read the file that contains the path to adb
		adbPath = os.readLine();//Read the first line of the text file
		System.out.println("Path to adb set as: "+adbPath); //alert the user
		
	}catch (FileNotFoundException e) {//if the os file is unavailable...
		// TODO Auto-generated catch block
		JOptionPane.showMessageDialog(null,
			    "Please make sure it's in the same folder\nYou're working in",
			    "'os' file not found!",
			    JOptionPane.WARNING_MESSAGE);
		System.exit(0); //close the program\
		   //TODO add a option to generate an OS file
		} catch (IOException e) {
		// TODO Auto-generated catch block
		//e.printStackTrace();  --maybe later
			JOptionPane.showMessageDialog(null,
				    "Sorry, but I can't read the file.\n Is it open somewhere?",
				    "Can't read os File!",
				    JOptionPane.WARNING_MESSAGE);
	}
	
	try{
		final Process adb = Runtime.getRuntime().exec(adbPath+" start-server");//startup adb
		//int ex =adb.waitFor();
		InputStream stdin = adb.getInputStream();//Makes an inputString 'stdin' that will contain the data from adb's output
		InputStreamReader adbRead = new InputStreamReader(stdin); //This InputStreamReader will read the data from out new inputString 'stdin'
		BufferedReader buffRead = new BufferedReader(adbRead);// 'buffRead will be the buffer for our InputStreamReader
		String conOutput = "";//A string that will hold the console's read and buffered output.
		String snglLine=null;//a single line read from out output, will be added to out full output 'conOutput'
		while ( (snglLine = buffRead.readLine()) != null){
            System.out.println(snglLine);
            conOutput=conOutput+snglLine+"\n";
			}
       // System.out.println("</OUTPUT>"+conOutput.indexOf("* daemon started successfully *"));
        int exitVal = adb.waitFor();
        if (exitVal ==0)//If we could get ADB to start
        	{
        	if(conOutput.indexOf("* daemon started successfully *")==-1)//If it returns -1  then ADB did not say "started successfully" So it must have been already running.
        		System.out.println("Adb was already running. cool!");
        	else														//if ADB said "started successfully" then adb was not running before (or out of date)
        		System.out.println("adb was not running, But I was able to start it for you!\nYou're welcome");
        	}
        else{//For some reason ADB could not be run
        	System.err.println("Fatail Error\n adb was found, but it could not be run.");
        	System.exit(-1);
        }
		

		} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		System.err.println("/n ADB may be missing! make sure it's in the same folder as this program");
		System.exit(0);
		}
	
}
	
public void showGUI() throws InterruptedException{
	mcp MCP =new mcp(adbPath);
	//ImageIcon beast = ImageIcon("beast.png");
	Object[] possibilities = {"Send Text", "Send Key presses", "Reboot Device",
							  "Reboot into Recovery","Foward ports","Install App",
							  "Send Files","Recive Files","Open URL","Close application"
							
								};
	
	while(!choice.equals("Close application")){
	 choice = (String)JOptionPane.showInputDialog(
	                    null,
	                    "Main Menu:\n"//Line 1
	                    + "What would you like to do?", //Line 2
	                    "adBeast "+ver,//Window Title
	                    JOptionPane.PLAIN_MESSAGE,
	                    null,
	                    possibilities,
	                    "Send Files");
	 
	 if (choice==null) //if they clicked cancel/close
		 System.exit(0);
		 
	 if (choice.equals("Reboot Device"))
			 MCP.reboot();

	 if (choice.equals("Reboot into Recovery"))
		 MCP.rebootRec();
	 
	 if (choice.equals("Open URL")){
		 usrInput = JOptionPane.showInputDialog(null, "Open what website?");
		 if (!(usrInput.equals(null))&&!(usrInput.equals("")))
			 MCP.openPage(usrInput);
	 	}
	
	 
	 if (choice.equals("Install App")){
		 browser.setFileFilter(apk);
		 browser.showOpenDialog(null);
		 usrInput=browser.getSelectedFile().getPath();
		 if (!(usrInput.equals(null))&&!(usrInput.equals("")))
			 MCP.download("\""+usrInput+"\"");		 
	 }
	 
	 if (choice.equals("Send Files")){
		 browser.setFileFilter(allFiles);
	 	 browser.showOpenDialog(null);
	 	 usrInput=browser.getSelectedFile().getName();
	 	 if (!(usrInput.equals(null))&&!(usrInput.equals("")))
	 	 	{
	 		usrInput2 = JOptionPane.showInputDialog(null, "To Where on device?","/sdcard/");
	 	 	if (!(usrInput2.equals(null))&&!(usrInput2.equals("")))
	 	 		MCP.push("\""+usrInput+"\"","\""+usrInput2+"\"");
	 	 	}
	 }
	 
	 
	 if (choice.equals("Foward ports")){
		 usrInput = JOptionPane.showInputDialog(null, "Forward what port? (device)","22");
	 	if (!(usrInput.equals(null))&&!(usrInput.equals(""))){
	 		usrInput2 = JOptionPane.showInputDialog(null, "To what port (PC) ?");
	 	 	if (!(usrInput2.equals(null))&&!(usrInput2.equals("")))
	 	 		MCP.prtFwd(Integer.parseInt(usrInput), Integer.parseInt(usrInput2));
	 		}
	 }
	 
	 
	 if(choice.equals("Recive Files")){
		 usrInput = JOptionPane.showInputDialog(null, "Pull what file? (Location on device)","/sdcard/");
	 	if (!(usrInput.equals(null))&&!(usrInput.equals(""))){
	 		usrInput2 = JOptionPane.showInputDialog(null, "Save to what folder? (PC)");
	 	 	if (!(usrInput2.equals(null))&&!(usrInput2.equals("")))
	 	 		MCP.pull(usrInput,usrInput2);
	 		}
	 	}
	 
	 if (choice.equals("Send Key presses")){
		System.out.println("starting key transmission component...");
		key_listener keyz =new key_listener();
		while(keyz.closed()==false){//wait for the key sender to be closed
			Thread.sleep(500);
			}
		keyz.reset();//then reset the closed variable				
	 	}
	
	 		
 }
}

@Override
public int getIconHeight() {
	// TODO Auto-generated method stub
	return 0;
}

@Override
public int getIconWidth() {
	// TODO Auto-generated method stub
	return 0;
}

@Override
public void paintIcon(Component arg0, Graphics arg1, int arg2, int arg3) {
	// TODO Auto-generated method stub
	
}
}